

<template>
    <div v-show="isShow">{{ resetTime }}</div>
</template>
<script setup lang="ts">
const resetTime = ref()
const isShow = ref(false)
const props = defineProps({
    time: { type: Number, default: 0 },
    format: { type: String }
})
const emit = defineEmits(["onFinished"])
const curDate = Date.now();
let timer: NodeJS.Timeout;
const start = () => {
    timer && clearInterval(timer);
    let time = props.time;
    if (("" + props.time).length === 10) {
        time = props.time * 1000;
    } else if (("" + props.time).length != 13) {
        return resetTime.value = "时间戳只能为10位或13位"
    }
    if (time - curDate > 0) {
        isShow.value = true;
        formatTimeDifference(time - curDate, props.format)
        time -= 1000;
        timer = setInterval(() => {
            formatTimeDifference(time - curDate, props.format);
            time -= 1000;
            if (time <= curDate) {
                emit("onFinished")
                clearInterval(timer)
                isShow.value = false;
            }

        }, 1000)
    }
}
function formatTimeDifference(endTimestamp: number, format = "HH:mm:ss") {
    const msPerSecond = 1000;
    const msPerMinute = 60 * 1000;
    const msPerHour = msPerMinute * 60;
    const msPerDay = msPerHour * 24;

    const days = Math.floor(endTimestamp / msPerDay);
    const hours = Math.floor((endTimestamp % msPerDay) / msPerHour);
    const minutes = Math.floor((endTimestamp % msPerHour) / msPerMinute);
    const seconds = Math.floor((endTimestamp % msPerMinute) / msPerSecond);

    const padZero = (num: number) => num.toString().padStart(2, '0');
    const o = {
        "DD": days,
        "HH": hours,
        "mm": minutes,
        "ss": seconds
    }

    Object.entries(o).forEach(([key, value]) => {
        format = format.replace(key, padZero(value))
    })
    resetTime.value = format
}

defineExpose({ start })
</script>


<style scoped></style>
